package com.espirit.eap.manager;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.espirit.eap.pagelayout.ResourceManagerService;
import com.espirit.eap.util.TaglibManager;
import com.googlecode.cswish.Config;
import com.googlecode.cswish.model.KeyValue;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.struts.spring.GenericService;

@Service
public class TaglibService {
	
	private static final Log logger = LogFactory.getLog(TaglibService.class);
	
	@Resource
	private Config config;
	
	@Resource
	private TaglibManager taglibManager;

	@Resource
	private GenericService genericService;
	
	@Resource
	private ResourceManagerService resourceManagerService;
	
	public void _update(Taglib model) {
		Taglib taglib = genericService.view(model);
		String path = taglib.getPath();
		String source = this.viewSource(path);
		model.setSource(source);
	}
	
	public String viewSource(String path){
		String webRootPath = config.getRealWebRootPath();
		File tagFile = new File(webRootPath + path);
		boolean hasTagFile = tagFile.exists();
		String source = "";
		if (hasTagFile) {
			try {
				source = FileUtils.readFileToString(tagFile);
			} catch (IOException e) {
				logger.error("Failed to load taglib file:" + path, e);
			}
		}
		return source;
	}
	
	
	public PageInfo searchTaglibFiles(Integer pageNo, Integer pageSize, String query){
		PageInfo pageInfo = null;
		String path = taglibManager.getTagFolder();
		String webRootPath = config.getRealWebRootPath();
		File tagFolder = new File(webRootPath + path);
		boolean hasTagFile = tagFolder.exists() && tagFolder.list().length > 0;
		if (hasTagFile) {
			List<KeyValue> results = new ArrayList<>();
			for (File taglibFile : tagFolder.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					// 1. only scan ftl file
					// 2. skip the control tag, such as if_control, when_control etc
					return name.endsWith(".ftl") && !name.endsWith("control.ftl");
				}
			})) {
				try {
					String relativePath = path + taglibFile.getName();
					KeyValue keyValue= new KeyValue(relativePath, relativePath);
					results.add(keyValue);
				} catch (Exception ex) {
					logger.error("Failed to read tag file:" + taglibFile, ex);
				}
			}
			
			if (!results.isEmpty()) {
				pageInfo = new PageInfo<>();
				pageInfo.setData(results);
				pageInfo.setPageNo(pageNo);
				pageInfo.setPageSize(config.getPageSize());
				pageInfo.setTotalCount(results.size());
			}
		}
		return pageInfo;
	}
}
